import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

Vue.use(Vuex)

// 循环引入modules文件
// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})
// 持久化储存
const myPlugin = store => {
  store.subscribe((mutation, state) => {
    let localid = mutation.type.split("/")[0] // 截取vuex标识
    let arr = ['permission'] // 不进行缓存
    if (!arr.includes(localid)) {
      window.localStorage.setItem(localid, JSON.stringify(state[localid]))
    }
  })
}

const store = new Vuex.Store({
  modules: modules,
  getters,
  plugins: [myPlugin]
})

export default store
